package cn.com.hp.feature.util;

import cn.com.hp.feature.exception.BussinessException;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author hjz
 * @description TODO
 * @date 2020/12/2217:12
 */
@Slf4j
@Component
public class RequestUtils {


    @Autowired
    private RestTemplate restTemplate;

    private final String HTTPMETHOD = "get";

    /**
     * 请求第三方接口
     *
     * @param hashMap       入参
     * @param getOrPost     请求方式
     * @param httpHeaders   头部
     * @param url           请求地址
     * @param responseClass 结果转换对象
     * @param <T>转换泛型
     * @return 请求结果
     */
    public <T> T request(Object hashMap, String getOrPost, HttpHeaders httpHeaders, String url, Class<T> responseClass) {
        HttpEntity httpEntity = new HttpEntity<>(hashMap, httpHeaders);
        log.info("request url:{}", url);
        log.info("request header:{}", httpEntity.getHeaders().toSingleValueMap());
        ResponseEntity<String> exchange = null;
        try {
            //执行请求
            if (HTTPMETHOD.equals(getOrPost)) {
                exchange = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);
            } else {
                exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);
            }
        } catch (Exception e) {
            log.error("调用远程服务异常：url:",url);
            log.error("调用远程服务异常信息",e);
            throw new BussinessException("46", "调用接口异常");
        }
        if (exchange.getStatusCodeValue() != HttpStatus.OK.value()) {
            throw new BussinessException("2", "调用远程服务超时");
        }
        T t = JSON.parseObject(exchange.getBody(), responseClass);
        return t;
    }

    public <T> T fileUploadRequest(MultiValueMap<String, Object> hashMap, MultipartFile file,
                                   String url, Class<T> responseClass,String contenType) {
        log.info("file upload start ===");
        log.info("file size ===" + file.getSize());

        String originalFilename = file.getOriginalFilename();
        HttpHeaders headers = new HttpHeaders();
        //headers.setContentType(MediaType.parseMediaType(contenType));
        //excel的请求头
        HttpHeaders excelHeader = new HttpHeaders();
        excelHeader.setContentType(MediaType.parseMediaType(contenType));
        excelHeader.setContentDispositionFormData("file", originalFilename);
        try {
            HttpEntity<ByteArrayResource> excelPart = new HttpEntity<>(new ByteArrayResource(file.getBytes()), excelHeader);
            hashMap.add("file", excelPart);
            //用HttpEntity封装整个请求报文
            HttpEntity<MultiValueMap<String, Object>> files = new HttpEntity<>(hashMap, headers);
            String resp = restTemplate.postForObject(url, files, String.class);
            log.info("file upload end ===");
            log.info("file upload result ===" + resp);
            T t = JSON.parseObject(resp, responseClass);
            return t;
        } catch (Exception e) {
            log.error("调用远程服务异常：url:", url);
            log.error("调用远程服务异常信息", e.getMessage());
            throw new BussinessException("46", "调用接口异常");

        }
    }

}
